package org.uim.cricket.analyzer.parsers.match.impl;

import java.util.HashMap;

import org.uim.cricket.analyzer.parsers.match.GroundParsable;
import org.uim.cricket.analyzer.parsers.misc.URLIDParsable;
import org.uim.cricket.entities.match.CricketMatch;
import org.uim.cricket.entities.match.Ground;
import org.uim.cricket.entities.match.Venue;
import org.uim.cricket.util.HTMLStringUtils;

public class DefaultGroundParser implements GroundParsable {

    private URLIDParsable urlIdParser = null;
    

    public DefaultGroundParser() {
        
    }
    
    public DefaultGroundParser(URLIDParsable theUrlIDparser) {
        this.urlIdParser = theUrlIDparser; 
    }
    
	@Override
	public Ground parseGround(String source, CricketMatch match) {
		if (source == null) return null;
		Ground ground = new Ground();
		
		int pos = source.indexOf('<');
		source = source.substring(pos);
		
		int epos = source.indexOf('>');
		String tag = source.substring(0, epos + 1);
		
		HashMap<String, String> attribs = HTMLStringUtils.getHTMLAttributes(tag);
		if (this.urlIdParser != null) {
		    ground.setId(urlIdParser.parseUrlID(attribs.get("href")));
		} else {
		    ground.setId(attribs.get("href"));
		}
		ground.setGroundLink(attribs.get("href"));
		
		source = HTMLStringUtils.cleanHTMLTags(source, true);
		if (source.indexOf("(neutral venue)") >= 0) {
			match.setVenue(Venue.NEUTRAL);
			source = source.replace("(neutral venue)", "").trim();
		}
		ground.setName(source);
		
		return ground;
	}
	
	public void setUrlIdParser(URLIDParsable urlIdParser) {
        this.urlIdParser = urlIdParser;
    }
	
	public URLIDParsable getUrlIdParser() {
        return urlIdParser;
    }

}
